<?php

namespace app\agent\model\agent;

use app\agent\model\BaseModel;


/**
 * 商家用户模型
 * Class StoreUser
 * @package app\store\model
 */
class AgentWxapp extends BaseModel{

    protected $name = 'agent_wxapp';


    /*
     * 获取小程序配置信息
     */
    public static function getInfo($agentId){

        $return=self::get(['agent_id'=>$agentId]);

        return $return;
    }
    /*
     * 添加
     */
    public function add($data,$agent_id){
        $data['agent_id'] = $agent_id;
        $data['createTime'] = time();
        $data['updateTime'] =  time();
        $data['status'] =  1;
        return $this->allowField(true)->save($data);
    }



    /**
     * 更新小程序配置信息
     */
    public function edit($data,$agent_id){

        $this->startTrans();
        try {
            // 写入微信支付证书文件
            $this->writeCertPemFiles($data['cert_pem'], $data['key_pem'],$agent_id);
            // 更新小程序设置
            $this->allowField(true)->save($data);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }

    /**
     * 写入cert证书文件
     * @param string $cert_pem
     * @param string $key_pem
     * @return bool
     */
    private function writeCertPemFiles($cert_pem = '', $key_pem = '',$agent_id)
    {

        if (empty($cert_pem) || empty($key_pem)) {
            return false;
        }

        // 证书目录
        $filePath = APP_PATH . 'common/library/wechat/agent/cert/' . $agent_id . '/';

        // 目录不存在则自动创建
        if (!is_dir($filePath)) {
            mkdir($filePath, 0755, true);
        }
        // 写入cert.pem文件
        if (!empty($cert_pem)) {
            file_put_contents($filePath . 'cert.pem', $cert_pem);
        }
        // 写入key.pem文件
        if (!empty($key_pem)) {
            file_put_contents($filePath . 'key.pem', $key_pem);
        }
        return true;
    }



}
